package com.qf.question01.interceptor;



import com.qf.question01.dao.UserDao;
import com.qf.question01.entity.User;
import com.qf.question01.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class NPWDInterceptor implements HandlerInterceptor {

    @Autowired
    UserDao userDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();

        Object attribute = session.getAttribute(Constants.USER_LOGIN_SESSION_KEY);

        if (attribute!=null){

            response.sendRedirect("/plateform.html");

            return true;
        }

        Cookie[] cookies = request.getCookies();

        if (cookies!=null && cookies.length>0) {
            for (Cookie cookie : cookies) {

                if (cookie.getName().equals(Constants.AUTOLOGIN_COOKIE_KEY)) {

                    String value = cookie.getValue();

                    String[] split = value.split("-");

                    String name = split[0];

                    String password = split[1];

                    User user = userDao.getUserBYNameAndPassword(name, password);

                    if (user != null) {

                        session.setAttribute(Constants.USER_LOGIN_SESSION_KEY, user);

                        response.sendRedirect("/plateform.html");

                        return false;
                    }
                }
            }
            return true;
        }

            return true;
    }
}
